package com.gitee.wsl.collections.iterator

/**
 * Decorates another iterator to skip the first N elements.
 *
 *
 * In case an offset parameter other than 0 is provided, the decorated
 * iterator is immediately advanced to this position, skipping all elements
 * before that position.
 *
 *
 * @param <E> the type of elements returned by this iterator.
 * @since 4.1
</E> */
class SkippingIterator<E>(val iterator: Iterator<E>, offset: Long) : Iterator<E>{
    /** The offset to bound the first element return  */
    private val offset: Long

    /** The position of the current element  */
    private var pos: Long

    /**
     * Decorates the specified iterator to skip all elements until the iterator
     * reaches the position at `offset`.
     *
     *
     * The iterator is immediately advanced until it reaches the position at `offset`,
     * incurring O(n) time.
     *
     * @param iterator  the iterator to be decorated
     * @param offset  the index of the first element of the decorated iterator to return
     * @throws NullPointerException if iterator is null
     * @throws IllegalArgumentException if offset is negative
     */
    init {
        require(offset >= 0) { "Offset parameter must not be negative." }

        this.offset = offset
        this.pos = 0
        init()
    }

    /**
     * Skips the given number of elements.
     */
    private fun init() {
        while (pos < offset && hasNext()) {
            next()
        }
    }

    public override fun next(): E {
        val next = iterator.next()
        pos++
        return next
    }

    override fun hasNext(): Boolean = iterator.hasNext()

    /**
     * {@inheritDoc}
     *
     *
     * In case an offset other than 0 was specified, the underlying iterator will be advanced
     * to this position upon creation. A call to [.remove] will still result in an
     * [IllegalStateException] if no explicit call to [.next] has been made prior
     * to calling [.remove].
     */
//    public override fun remove() {
//        check(pos > offset) { "remove() cannot be called before calling next()" }
//        super.remove()
//    }
}